package com.ancun.dao;

import com.ancun.entity.Girl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;

public interface GirlRepository extends JpaRepository<Girl, Integer>, JpaSpecificationExecutor<Girl>
{
    public List<Girl> findByAge(Integer age);

    // modifying时必须transactional, 必须有否则会报错
    // 抛出异常TranscationRequiredException
    @Transactional
    @Modifying
    @Query(value = "update Girl g set g.age = ?1, g.name = ?2 where g.id = ?3", nativeQuery = true)
    public int modifyAgeAndNameById(int age, String name, int id);

    // nativeQuery = true使用原生SQL，否则默认false，使用HQL
    // HQL不能select *,必须select g
    @Query(value = "select g from Girl as g where g.name = ?1")//, nativeQuery = true)
    public List<Girl> findByName(String name);

    // 按名称分页排序
    // org.springframework.data.domain.Pageable
    // 注意是这个Pageable，还有一个叫 java.awt.print.Pageable
    public Page<Girl> findByName(String name, Pageable pageable);

    // HQL的分页排序
    @Query(value = "select g from Girl as g where g.age = ?1")
    public Page<Girl> findByAge(int age, Pageable pageable);
}
